package com.tusuo.stds.ui.bindthird;

import android.content.Context;

import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.tusuo.stds.Constants;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.ApiResult;
import com.tusuo.stds.util.Utils;

import java.util.HashMap;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import rx.Subscriber;

/**
 * @author J.Huang
 * @version 1.1
 *
 */

@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(BindThirdPresenter.class)
class BindThirdPresenter extends MvpBasePresenter<BindThirdView> {

    @Inject
    ApiHelper mApiHelper;

    private Context mContext;
    private String mErrMsgServer;

    private Subscriber<ApiResult> mBindWechatSubscriber = null;
    private Subscriber<ApiResult> mBindQQSubscriber = null;
    private Subscriber<ApiResult> mBindWeiboSubscriber = null;
    private Subscriber<ApiResult> mUnbindWechatSubscriber = null;
    private Subscriber<ApiResult> mUnbindQQSubscriber = null;
    private Subscriber<ApiResult> mUnbindWeiboSubscriber = null;

    BindThirdPresenter(Context context) {
        mContext = context;
        mErrMsgServer = mContext.getResources().getString(R.string.err_msg_server);

        Injector.initBindThirdPresenterComponent().inject(this);
    }

    @Override
    public void detachView(boolean retainInstance) {
        if (mBindWechatSubscriber != null) {
            mBindWechatSubscriber.unsubscribe();
            mBindWechatSubscriber = null;
        }
        if (mBindQQSubscriber != null) {
            mBindQQSubscriber.unsubscribe();
            mBindQQSubscriber = null;
        }
        if (mBindWeiboSubscriber != null) {
            mBindWeiboSubscriber.unsubscribe();
            mBindWeiboSubscriber = null;
        }
        if (mUnbindWechatSubscriber != null) {
            mUnbindWechatSubscriber.unsubscribe();
            mUnbindWechatSubscriber = null;
        }
        if (mUnbindQQSubscriber != null) {
            mUnbindQQSubscriber.unsubscribe();
            mUnbindQQSubscriber = null;
        }
        if (mUnbindWeiboSubscriber != null) {
            mUnbindWeiboSubscriber.unsubscribe();
            mUnbindWeiboSubscriber = null;
        }
        super.detachView(retainInstance);
    }

    //执行授权,获取用户信息
    //文档：http://wiki.mob.com/Android_%E8%8E%B7%E5%8F%96%E7%94%A8%E6%88%B7%E8%B5%84%E6%96%99
    private void authorize(final Platform plat, final String platformCode) {
        if (plat == null) {
            return;
        }

        plat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int action, HashMap<String, Object> res) {

                if (action == Platform.ACTION_USER_INFOR) {
                    PlatformDb platDB = platform.getDb();//获取数平台数据DB
                    // 别放Toast! ShareSDK会报错！
                    switch (platformCode) {
                        case Constants.PLATFORM.WECHAT:
                            mBindWechatSubscriber = new BindThirdSubscriber(platformCode);
                            mApiHelper.bindCurrent(mBindWechatSubscriber,
                                    platDB.getUserId(),
                                    platformCode,
                                    platDB.getToken(),
                                    platDB.getUserName(),
                                    platDB.getUserIcon());
                            break;
                        case Constants.PLATFORM.QQ:
                            mBindQQSubscriber = new BindThirdSubscriber(platformCode);
                            mApiHelper.bindCurrent(mBindQQSubscriber,
                                    platDB.getUserId(),
                                    platformCode,
                                    platDB.getToken(),
                                    platDB.getUserName(),
                                    platDB.getUserIcon());
                            break;
                        case Constants.PLATFORM.WEIBO:
                            mBindWeiboSubscriber = new BindThirdSubscriber(platformCode);
                            mApiHelper.bindCurrent(mBindWeiboSubscriber,
                                    platDB.getUserId(),
                                    platformCode,
                                    platDB.getToken(),
                                    platDB.getUserName(),
                                    platDB.getUserIcon());
                            break;
                        default:
                            break;
                    }

                } else {
                    resetBindingStatus(platformCode);
                }
            }

            @Override
            public void onError(Platform platform, int action, Throwable throwable) {
                if (action == Platform.ACTION_USER_INFOR) {
                    PlatformDb platDB = platform.getDb();//获取数平台数据DB
                    // 别放Toast! ShareSDK会报错！
                    switch (platformCode) {
                        case Constants.PLATFORM.WECHAT:
                            mBindWechatSubscriber = new BindThirdSubscriber(platformCode);
                            mApiHelper.bindCurrent(mBindWechatSubscriber,
                                    platDB.getUserId(),
                                    platformCode,
                                    platDB.getToken(),
                                    platDB.getUserName(),
                                    platDB.getUserIcon());
                            break;
                        case Constants.PLATFORM.QQ:
                            mBindQQSubscriber = new BindThirdSubscriber(platformCode);
                            mApiHelper.bindCurrent(mBindQQSubscriber,
                                    platDB.getUserId(),
                                    platformCode,
                                    platDB.getToken(),
                                    platDB.getUserName(),
                                    platDB.getUserIcon());
                            break;
                        case Constants.PLATFORM.WEIBO:
                            mBindWeiboSubscriber = new BindThirdSubscriber(platformCode);
                            mApiHelper.bindCurrent(mBindWeiboSubscriber,
                                    platDB.getUserId(),
                                    platformCode,
                                    platDB.getToken(),
                                    platDB.getUserName(),
                                    platDB.getUserIcon());
                            break;
                        default:
                            break;
                    }

                } else {
                    resetBindingStatus(platformCode);
                }
            }

            @Override
            public void onCancel(Platform platform, int action) {
                resetBindingStatus(platformCode);
            }
        });

        // 登录的时候走客户端,如果没有客户端会调转到网页版
        plat.SSOSetting(false);
        plat.showUser(null);//执行登录，登录后在回调里面获取用户资料
    }

    // 取消授权
    private void cancelAuth(String platformCode){
        Platform platform = null;

        switch (platformCode) {
            case Constants.PLATFORM.WECHAT:
                platform = ShareSDK.getPlatform(Wechat.NAME);
                break;
            case Constants.PLATFORM.QQ:
                platform = ShareSDK.getPlatform(QQ.NAME);
                break;
            case Constants.PLATFORM.WEIBO:
                platform = ShareSDK.getPlatform(SinaWeibo.NAME);
                break;
            default:
                break;
        }

        if (platform != null) {
            if (platform.isAuthValid()) {
                platform.removeAccount(true);
                ShareSDK.removeCookieOnAuthorize(true);
            }
            Utils.UI.showToastShort("账户解绑中,请稍后...");
        }
    }

    void bindWechat() {
        String platformCode = Constants.PLATFORM.WECHAT;
        Platform weChat = ShareSDK.getPlatform(Wechat.NAME);
        authorize(weChat, platformCode);
    }

    void unbindWechat() {
        String platformCode = Constants.PLATFORM.WECHAT;
        mUnbindWechatSubscriber = new UnbindThirdSubscriber(platformCode);
        mApiHelper.unbindThird(mUnbindWechatSubscriber, platformCode);
    }

    void bindQQ() {
        String platformCode = Constants.PLATFORM.QQ;
        Platform qq = ShareSDK.getPlatform(QQ.NAME);
        authorize(qq, platformCode);
    }

    void unbindQQ() {
        String platformCode = Constants.PLATFORM.QQ;
        mUnbindQQSubscriber = new UnbindThirdSubscriber(platformCode);
        mApiHelper.unbindThird(mUnbindQQSubscriber, platformCode);
    }

    void bindWeibo() {
        String platformCode = Constants.PLATFORM.WEIBO;
        Platform sinaWeibo = ShareSDK.getPlatform(SinaWeibo.NAME);
        authorize(sinaWeibo, platformCode);
    }

    void unbindWeibo() {
        String platformCode = Constants.PLATFORM.WEIBO;
        mUnbindWeiboSubscriber = new UnbindThirdSubscriber(platformCode);
        mApiHelper.unbindThird(mUnbindWeiboSubscriber, platformCode);
    }

    private void resetBindingStatus(String platform) {
        if (getView() != null) {
            switch (platform) {
                case Constants.PLATFORM.WECHAT:
                    getView().rollbackWechatBindStatus();
                    break;
                case Constants.PLATFORM.QQ:
                    getView().rollbackQQBindStatus();
                    break;
                case Constants.PLATFORM.WEIBO:
                    getView().rollbackWeiboBindStatus();
                    break;
                default:
                    break;
            }
        }
    }

    private class BindThirdSubscriber extends Subscriber<ApiResult> {
        String mPlatform;

        BindThirdSubscriber(String platform) {
            mPlatform = platform;
        }

        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            resetBindingStatus(mPlatform);
            Utils.UI.showToastShort(mErrMsgServer);
        }

        @Override
        public void onNext(final ApiResult result) {
            if (!result.checkState(mContext)) {
                resetBindingStatus(mPlatform);
            } else {
            }
        }
    }

    private class UnbindThirdSubscriber extends Subscriber<ApiResult> {
        String mPlatform;

        UnbindThirdSubscriber(String platform) {
            mPlatform = platform;
        }

        @Override
        public void onCompleted() {
            cancelAuth(mPlatform);
        }

        @Override
        public void onError(Throwable e) {
            resetBindingStatus(mPlatform);
            Utils.UI.showToastShort(mErrMsgServer);
        }

        @Override
        public void onNext(final ApiResult result) {
            if (!result.checkState(mContext)) {
                resetBindingStatus(mPlatform);
            }
        }
    }
}
